<?php
ini_set("yar.timeout",60000);

require_once 'PicThumb.class.php';

class PatternService extends TP_Service {
    private $role;
    private $client;
    public function __construct() {
        parent::__construct();
        $this->load->model("SModel/Pattern_model");
        $this->load->model("SModel/Pattern_property_model");
        $this->load->model("SModel/Property_model");
        $this->load->service("PService/UploadService");
        $this->load->service("PService/ExportExcelService");
        $this->load->model("SModel/Config_model");
        $this->load->Model("PModel/Account_model");
		$this->load->model("SModel/Customer_model");
        $this->load->Model("PModel/V_Admin_model");
        $this->role = $this->getRole($_SESSION[SESS_UUID]);
        $this->client = new Yar_Client($this->config->item('rpc')['url']);
    }

    /**
     * 方法名 patternList
     *
     * @Name 获取方法列和角色方法列
     * @Desc 花型列表
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     */
    public function patternList($param, $export = false) {
    	$is_public = $param['is_public'];

        $adminlist = $this->getAdminList(); //所有用户
        $new_admin_list =array();
        foreach($adminlist as $k=>$v){
            $new_admin_list[$v['value']] = $v['label'];
        }

        if (!$export) {
            $param = array_filter($param);
            if (!isset($param['pageNo'], $param['pageSize'])) {
                exit(retJson(ErrCode::ErrCode_10002));
            }

            $conarr['pageNo'] = $param['pageNo'];
            $conarr['pageSize'] = $param['pageSize'];
        }
        $param['is_public'] = $is_public;

        $conarr['items'] = "*";
        $conarr['orderby'] = "created desc";
        $conarr['where'] = "1 = 1";


        // 搜索
        if (!empty($param['no'])) {
            $conarr['where'] .= sql_format(" AND no LIKE '%{0}%'", $param['no']);
        }
        if (!empty($param['level'])) {
            $conarr['where'] .= sql_format(" AND level = '{0}'", $param['level']);
        }
        if (!empty($param['stock'])) {
            $conarr['where'] .= sql_format(" AND stock = '{0}'", $param['stock']);
        }
        if (!empty($param['height'])) {
            $conarr['where'] .= sql_format(" AND height = '{0}'", $param['height']);
        }
        if (!empty($param['weight'])) {
            $conarr['where'] .= sql_format(" AND weight = '{0}'", $param['weight']);
        }
        if (!empty($param['created']) && is_array($param['created'])) {
            $conarr['where'] .= sql_format(" AND created BETWEEN '{0}' AND '{1}'", $param['created'][0], $param['created'][1]);
        }
        if (!empty($param['updated']) && is_array($param['updated'])) {
            $conarr['where'] .= sql_format(" AND updated BETWEEN '{0}' AND '{1}'", $param['updated'][0], $param['updated'][1]);
        }
        if (!empty($param['publish_time']) && is_array($param['publish_time'])) {
            $conarr['where'] .= sql_format(" AND publish_time BETWEEN '{0}' AND '{1}'", $param['publish_time'][0], $param['publish_time'][1]);
        }

		if (intval($param['is_public']) == 1) {
			$conarr['where'] .= sql_format(" AND is_public = '{0}'", $param['is_public']);
		}

		if (intval($param['is_public']) == 0) {
			$conarr['where'] .= sql_format(" AND (is_public = '{0}' OR is_public is NULL)", $param['is_public']);
		}

        if ($export) {
            $list = $this->Pattern_model->get_list_full($conarr);
            $this->getDynamicField($list);
        } else {
            $list = $this->Pattern_model->get_page_list($conarr);


            $url = 'http://';
            if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
                $url = 'https://';
            }
            $url .= $_SERVER['HTTP_HOST'].'/'  ;

            foreach ($list['ret'] as $key => &$value) {
                $value['plates'] = json_decode($value['plates'], true);
                $picture = [];
                $picture[] = array('url' => $url . $value['picture']);
                if (!empty($value['otherImg'])) {
                    $otherimg = explode(",", $value['otherImg']);
                    foreach ($otherimg as $k1 => $v1) {
                        $picture[] = array('url' => $url . $v1);
                    }
                }


            //    $value['picture'] = $picture;
                if (!empty($value['picture_thumb'])) {
					$value['picture_thumb'] = $url . $value['picture_thumb'];
				}

                $value['publicDate'] = date("Y-m", strtotime($value['public']));
                //查询查看人
                if($value['viewId'] != null ||  $value['viewId'] != ""){
                    $viewName=array();
                    foreach(explode(",", $value['viewId']) as $k2=>$v2){
                        if($k2<3){
                            $viewName[] = $new_admin_list[$v2];
                        }else{
                            $viewName[] = '...';
                        }  
                    } 
                    $viewName = array_unique($viewName);
                    $list['ret'][$key]['viewId'] =   explode(",", $value['viewId']);
                    $list['ret'][$key]['viewName'] =   implode(",",$viewName);
                }else{
                    $list['ret'][$key]['viewId'] =  [];
                    $list['ret'][$key]['viewName'] =  '';
                }

            }
           
            $this->getDynamicField($list['ret']);
        }
        return $list;
    }

    private function getDynamicField(&$arr) {
        if (!is_array($arr) || empty($arr)) {
            return;
        }

        foreach ($arr as &$value) {
            $where = sql_format("pid = '{0}'", $value['pid']);
            $dynamic = $this->Pattern_property_model->get_list_full(['items' => 'property_key, property_name, property_value', 'where' => $where]);
            foreach ($dynamic as $v) {
                $json = json_decode($v['property_value'], true);
                $value[$v['property_key']] = $json['value'];
            }
            // $value['similarity_value'] = '0';//相似值赋值
        }

    }

    // 能否操作
    private function hasPre() {
        if ($this->role->role_id != WebRole::Manage[TPEnum::Value]) {
            exit(retJson(ErrCode::ErrCode_10404));
        }
    }


    /**
     * 方法名 patternDelete
     *
     * @Name 获取方法列和角色方法列
     * @Desc 花型删除
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     */
    public function patternDelete($param) {
        if (!isset($param['pid']) || empty($param['pid'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        $this->hasPre();

		$pattern = $this->Pattern_model->get_single(array('pid' => $param['pid']));
		if ($pattern && $pattern['picture'] != '') {
			if (file_exists( $pattern['picture'])) {
				$post_data = [
					'points' => $this->config->item('project_dir') . $pattern['picture'],
                    'patternNo'=>$pattern['no'],
                    'patternId'=>$pattern['pid'],
				];
				$this->curl_post($this->config->item('cbir_url') . 'cbir_delete', $post_data);
			}
		}

        $this->Pattern_model->delete(['pid' => $param['pid']],true);
        $this->Pattern_property_model->delete(['pid' => $param['pid']],true);

        $this->client->delIndex($pattern['no']);

        return true;
    }


    /**
     * 方法名 patternInfo
     *
     * @Name 获取方法列和角色方法列
     * @Desc 花型详情
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     */
    public function patternInfo($param) {
        if (!isset($param['pid']) || empty($param['pid'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        $where = sql_format("pid = '{0}'", $param['pid']);
        $info = $this->Pattern_model->get_single_full(['where' => $where]);
        if (empty($info)) {
            return [];
        }
        $info['plates'] = json_decode($info['plates'], true);
        $dynamic = $this->Pattern_property_model->get_list_full(['items' => 'property_key, property_name, property_value', 'where' => $where]);
        foreach ($dynamic as $v) {

            $json = json_decode($v['property_value'], true);

            if (is_array($json['value'])) {
                $json['value'] = implode("，", $json['value']);
            }
            $info[$v['property_key']] = $json['value'];
        }
         // $info['sealingText'] = $info['is_sealing'] == 1 ? "已封" : "未封";

        $info['similarity_value'] = $param['similarity_value'];//相似值赋值
        
        $info['FlowersStock'] = $this->getPatternInfoList($info['no']);

        // var_dump($info);
        return $info;
    }


    //根据花型型号查询花型详情
    public function getPatternInfoList($wuliaoname){
        $configDateBase =  $this->config->item('sqlServerDatabase');
        $conn = new PDO("sqlsrv:server=".$configDateBase['server'].";database=".$configDateBase['database'],$configDateBase['uid'],$configDateBase['pwd']);
        $sql = "select * from vWmmHGSearchFlowersStock where 物料名称='".$wuliaoname."'";
        $res = $conn->query($sql);
        $newArr = array();
        $i =0;
        while ($row = $res->fetch()){
            $newArr[$i]['wlmc'] = $row['物料名称']?$row['物料名称']:'';
            $newArr[$i]['ys'] = $row['颜色']?$row['颜色']:'';
            $newArr[$i]['khsh'] = $row['客户色名']?$row['客户色名']:'';
            $newArr[$i]['kahao'] = $row['卡号']?$row['卡号']:'';
            $newArr[$i]['xianghao'] = $row['箱号']?$row['箱号']:'';
            $newArr[$i]['kuwei'] = $row['库位']?$row['库位']:'';
            $newArr[$i]['dengji'] = $row['等级']?$row['等级']:'';
            $newArr[$i]['kczl'] = $row['库存重量']?$row['库存重量']:'';
            $newArr[$i]['kccd'] = $row['库存长度']?$row['库存长度']:'';
            $newArr[$i]['dw'] = $row['单位']?$row['单位']:'';
            $newArr[$i]['zwrq'] = $row['最晚日期']?$row['最晚日期']:'';
            $newArr[$i]['ckmc'] = $row['仓库名称']?$row['仓库名称']:'';
            $newArr[$i]['kclx'] = $row['库存类型']?$row['库存类型']:'';
            $newArr[$i]['bl'] = $row['布类']?$row['布类']:'';
            $newArr[$i]['jx'] = $row['机型']?$row['机型']:'';
            $newArr[$i]['pdys'] = $row['排单余数']?$row['排单余数']:'';
            $newArr[$i]['lfts'] = $row['两幅条数']?$row['两幅条数']:'';
            $i++;
        }
        return  $newArr;
    }


    /**
     * 方法名 patternPublic
     *
     * @Name 获取方法列和角色方法列
     * @Desc 花型公布
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     */
    public function patternPublic($param) {
        if (!isset($param['pid']) || empty($param['pid'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        $this->hasPre();

        $this->Pattern_model->update(['is_public' => EnableState::Enable[TPEnum::Value], 'publish_time' => time()], ['pid' => $param['pid']]);
        return true;
    }


    /**
     * 方法名 patternImport
     *
     * @Name 获取方法列和角色方法列
     * @Desc 花型导入
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     */
    public function patternImport() {
        $this->hasPre();

        if (empty($_FILES)) {
            exit(retJson(ErrCode::ErrCode_10601));
        }


        $path = $this->UploadService->UploadFile('studentSource', true);
        $excellist =  $this->ExportExcelService->importexcel($path, 'AE', 'A', 2);
        if (count($excellist) == 0) {
            exit(retJson(ErrCode::ErrCode_10602));
        }

        //去掉空数组
        foreach ($excellist as $key => &$value) {
            // $value = array_filter($value, 'filtrfunction');
           if(empty($value['D'])){
               unset($excellist[$key]);
           }
        }
        // $excellist = array_filter($excellist);




        $con['items'] = "pid,no";
        $pattern = $this->Pattern_model->get_list_full($con);

        $pat = [];
        foreach ($pattern as $item) {
            $pat[$item['no']] = $item;
        }


        $nos = [];
        foreach ($excellist as $k2 => $item1) {
            if (isset($pat[$item1['D']])) {
                exit($this->retJson("第" . ($k2 + 2) . "行", ErrCode::ErrCode_10603));
            }

            foreach(explode(',', $item1['AB']) as $v3){
                if(!empty($v3) && !in_array($v3,["100","1000","2000","3000","4000","5000","6000"])){
                    exit($this->retJson("第" . ($k2 + 2) . "行", ErrCode::ErrCode_10907));
                }
            }
            $nos[] = $item1['D'];
        }


        $type = [
            'N' => ['key' => 'purpose', 'name' => '用途', 'is_multiple' => 0],
            'O' => ['key' => 'design', 'name' => '款式', 'is_multiple' => 0],
            'P' => ['key' => 'series', 'name' => '系列', 'is_multiple' => 0],
            'Q' => ['key' => 'material_science', 'name' => '材料', 'is_multiple' => 1],
            'R' => ['key' => 'elastic', 'name' => '弹性', 'is_multiple' => 0],
            'S' => ['key' => 'wave_edge', 'name' => '波边', 'is_multiple' => 1],
            'T' => ['key' => 'model', 'name' => '机型', 'is_multiple' => 0],
            'U' => ['key' => 'radio_station', 'name' => '机台针数', 'is_multiple' => 0],
            'V' => ['key' => 'function', 'name' => '功能', 'is_multiple' => 0],
            'W' => ['key' => 'style', 'name' => '风格', 'is_multiple' => 1],
            'X' => ['key' => 'texture', 'name' => '质感', 'is_multiple' => 0],
            'Y' => ['key' => 'element', 'name' => '元素描述', 'is_multiple' => 1],
            'Z' => ['key' => 'structure', 'name' => '结构', 'is_multiple' => 0],
        ];

        $data = [];
        $add = [];

        // //导入花型
        foreach ($excellist as $v) {
            $time = strtotime((int)$v['A'] . '-' . (int) $v['B']);
            $date = date('Y-m-15', $time);

            $plate = [];
            if (!empty($v['AB'])) {
                $continent = explode(',', $v['AB']);
                foreach ($continent as $key => $value) {

                    if ($value == 100) {
                        $plate[] = [$value];
                    } else {
                        $plate[] = ["100", $value];
                    }
                }
            }
            if (!empty($v['AC'])) {
                $p = explode(',', $v['AC']);
                foreach ($p as $key => $value) {
                    $father = substr($value, 0, 1) * 1000;
                    $plate[] = [
                        "100", "$father", "$value"
                    ];
                }
            }
            if (!empty($v['AD'])) {
                $p = explode(',', $v['AD']);
                foreach ($p as $key => $value) {
                    $plate[] = [
                        "100", "1000","1001", "$value"
                    ];
                }
            }


            $areas = '';

            $children = [];
            $childrenF = [];
            $fathers = [];

            foreach ($plate as $value) {
                if (count($value) == 1) {
                    $fathers[$value[0]] = $value[0];
                    $areas .= "$value[0],";
                } else {
                    $children[] = $value;
                }
            }
            if (!empty($children)) {
                foreach ($children as $value) {
                    if (count($value) == 2) {
                        if (!isset($fathers[$value[0]])) {
                            $fathers[$value[1]] = $value[1];
                            $areas .= "$value[1],";
                        }
                    } else {
                        $childrenF[] = $value;
                    }
                }
            }


            if (!empty($childrenF)) {
                foreach ($childrenF as $value) {
                    if (count($value) == 3) {
                        if (!isset($fathers[$value[0]]) && !isset($fathers[$value[1]])) {
                            $areas .= "$value[2],";
                        }
                    }else{
                        if (!isset($fathers[$value[0]]) && !isset($fathers[$value[1]]) && !isset($fathers[$value[2]])) {
                            $areas .= "$value[3],";
                        }
                    }
                }
            }
            $areas = rtrim($areas, ',');
            $add[] = array(
                // 'title'       => $v['A'],
                'is_valid'    => $v['C'] == '是' ? 1 : 0,
                'no'          => $v['D'],
                'stock'       => $v['E'],
                'unit'        => $v['F'],
                'factory'     => $v['G'],
                'height'      => $v['H'],
                'weight'      => $v['I'],
                'level'       => $v['J'],
                'component'   => $v['K'],
                'widthheight' => $v['L'],
                'widthlow'    => $v['M'],
                'public'      => $date,
                'sealingPlate' => $areas,
                'plates'      => json_encode($plate, JSON_UNESCAPED_UNICODE),
                'sealing_status' => empty($v['AA']) ? "未封板" : $v['AA'] ,
                'sealing_time' => $v['AE'],
                'created'     => date('Y-m-d H:i:s'),
            );
        }

        $this->Pattern_model->add($add);

        $conarr['items'] = "pid,no";
        $conarr['where'] = sql_format("created >= '{0}' and created <= '{1}'", date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59'));
        $res = $this->Pattern_model->get_list_full($conarr);

        $pids = [];
        foreach ($res  as $item2) {
            $pids[$item2['no']] = $item2['pid'];
        }


        // $this->db->trans_start();

        //导入花型属性
        foreach ($excellist as $v2) {
            foreach ($type as $k => $v1) {
                if ($v1['is_multiple'] == 1) {
                    $arr = explode(',', $v2[$k]);
                    $data[] = array(
                        'pid' => $pids[$v2['D']],
                        'property_key' => $v1['key'],
                        'property_name' => $v1['name'],
                        'property_value' => json_encode(array('value' => $arr), JSON_UNESCAPED_UNICODE)
                    );
                } else {
                    $data[] = array(
                        'pid' =>  $pids[$v2['D']],
                        'property_key' => $v1['key'],
                        'property_name' => $v1['name'],
                        'property_value' => json_encode(array('value' => $v2[$k]), JSON_UNESCAPED_UNICODE)
                    );
                }
            }
            //每500条花型 执行一次sql 语句
            // if (count($data) % (count($type) * 500) == 0) {
            //     $this->Pattern_property_model->add($data);
            //     $data = [];
            //     $this->db->trans_complete();
            //     $this->db->trans_start();
            // }
        }

        $this->Pattern_property_model->add($data);
        // $this->db->trans_complete();


        $addPids = "";
        foreach ($nos as $key => $value) {
            if(isset($pids[$value])){
                $addPids .= empty($addPids) ? $pids[$value] : ','.$pids[$value];
            }
        }
        $this->client->addIndex($addPids, '');
        return true;
    }


    /**
     * getProperty
     *
     * @Name getProperty
     * @Desc 获取动态属性
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      DJC
     * @Date 2022-02-15 18:16:57
     * @return      [type]                   [description]
     */
    public function getProperty() {
        $conarr['items'] = "id,key,key_name,value,is_multiple,is_required";
        $conarr['where'] = sql_format("is_status = '{0}'", 0);

        $list = $this->Property_model->get_list_full($conarr);
        foreach ($list as $k => &$v) {
            $v['value'] = json_decode($v['value']);
            $v['is_required'] = $v['is_required'] == '1';
            true;
            false;
        }
        return $list;
    }


    public function patternAdd($param) {
        if (!isset(
            $param['is_valid'],
            $param['is_public'],
            $param['no'],
            $param['stock'],
            $param['picture'],
            $param['unit'],
            $param['factory'],
            $param['height'],
            $param['weight'],
            $param['component'],
            $param['level'],
            $param['widthheight'],
            $param['widthlow'],
            $param['sealing_status'],

            // $param['region'],
            // $param['country'],
            // $param['customer_name'],
            // $param['customer_number'],
            $param['is_sealing'],
            $param['viewId']

            // $param['sealing_time'],
        )) {
            exit(retJson(ErrCode::ErrCode_10002));
        }


        $url = 'http://';
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
            $url = 'https://';
        }
        $url .= $_SERVER['HTTP_HOST'] . '/';


        //        $picture = str_replace($url, '', $param['picture']['0']['url']);
        //        $otherimg = "";
        //        $addpimg = $picture;
        //        if (count($param['picture']) > 1) {
        //            for ($i = 1; $i < count($param['picture']); $i++) {
        //                $otherimg .= empty($otherimg) ? str_replace($url, '', $param['picture'][$i]['url']) : ',' . str_replace($url, '', $param['picture'][$i]['url']);
        //                $addpimg .= '|' . str_replace($url, '', $param['picture'][$i]['url']);
        //            }
        //        }



        // 终端销售区域数据
        $areas = '';
        foreach ($param['plates'] as $value) {
            if (count($value) == 1) {
                $father[$value[0]] = $value[0];
                $areas .= "$value[0],";
            } else {
                $children[] = $value;
            }
        }
        if (isset($children)) {
            foreach ($children as $value) {
                if (count($value) == 2) {
                    if (!isset($father[$value[0]])) {
                        $father[$value[1]] = $value[1];
                        $areas .= "$value[1],";
                    }
                } else {
                    $childrenF[] = $value;
                }
            }
        }


        if (isset($childrenF)) {
            foreach ($childrenF as $value) {

                if (count($value) == 3) {

                    if (!isset($father[$value[0]]) && !isset($father[$value[1]])) {
                        $areas .= "$value[2],";
                    }
                }else{
                    if (!isset($father[$value[0]]) && !isset($father[$value[1]]) && !isset($father[$value[2]])) {
                        $areas .= "$value[3],";
                    }
                }
            }
        }

        $areas = rtrim($areas, ',');



        $sales_area = json_encode($param['plates'], JSON_UNESCAPED_UNICODE);
        $data = array(
            'is_valid' => $param['is_valid'],
            'is_public' => $param['is_public'],
            'no' => $param['no'],
            'stock' => $param['stock'],
            'picture' => $param['picture'],
            'unit' => $param['unit'],
            'factory' => $param['factory'],
            'height' => $param['height'],
            'weight' => $param['weight'],
            'component' => $param['component'],
            'level' => $param['level'],
            'widthheight' => $param['widthheight'],
            'widthlow' => $param['widthlow'],
            'sealingPlate' => $areas,
            'plates' => $sales_area,
            'series' => $param['series'],
            'otherImg' => $param['picture'],
            'sealing_status' => $param['sealing_status'],
            'viewId'=> count($param['viewId'])>0?implode(",", $param['viewId']):''
            
        );


        if ($param['is_public'] == 1) {
            $data['publish_time'] = date('Y-m-d H:i:s');
        } else {
			$data['publish_time'] = null;
		}

        if (isset($param['publicDate']) && $param['publicDate'] != '') {
			$data['public'] = $param['publicDate'] . '-15';
		}

        if (isset($param['pid'])) {
        	// 更新花型
            $conarr['where'] = sql_format("pid != '{0}' AND no = '{1}'", $param['pid'], $param['no']);
            $no = $this->Pattern_model->get_single_full($conarr);
            if ($no) {
                exit(retJson(ErrCode::ErrCode_10603));
            }

            // 处理缩略图
			$option = array(
				'type' => 'fit',
				'width' => 330,
				'height' => 240,
				'handler' => 'gd'
			);

			$source = $param['picture'];

			if (file_exists($source)) {
				$thumb_file = dirname($source) . '/' . $param['no']. '_thumb.jpg';

				$thumb = new PicThumb();
				$thumb->set_config($option);
				$thumb->create_thumb($source, $thumb_file);

				// 重命名文件
				rename($source, dirname($source) . '/' . $param['no']. '.jpg');
				$data['picture'] = dirname($source) . '/' . $param['no']. '.jpg';
				$data['picture_thumb'] = $thumb_file;
			}

            $this->Pattern_model->update($data, array('pid' => $param['pid']));

            $this->Pattern_property_model->delete(array('pid' => $param['pid']), true);

            $pid = $param['pid'];

			try {
				if (file_exists($data['picture'])) {
					$post_data = [
						'points' => $this->config->item('project_dir') . $data['picture'],
                        'patternNo'=>$param['no'],
                        'patternId'=> $pid,
					];
					$this->curl_post($this->config->item('cbir_url') . 'cbir_update', $post_data);
				}
			} catch (Exception $exception) {
				print_r($exception);
			}
        } else {
        	// 添加花型
            $no = $this->Pattern_model->get_single(array('no' => $param['no']));
            if ($no) {
                exit(retJson(ErrCode::ErrCode_10603));
            }

            // 处理缩略图
			$option = array(
				'type' => 'fit',
				'width' => 330,
				'height' => 240,
				'handler' => 'gd'
			);

			$source = $param['picture'];

            if (file_exists($source)) {
				$thumb_file = dirname($source) . '/' . $param['no']. '_thumb.jpg';

				$thumb = new PicThumb();
				$thumb->set_config($option);
				$thumb->create_thumb($source, $thumb_file);

				// 重命名文件
				rename($source, dirname($source) . '/' . $param['no']. '.jpg');
				$data['picture'] = dirname($source) . '/' . $param['no']. '.jpg';
				$data['picture_thumb'] = $thumb_file;
			}

			// $thumb_file = dirname($source) . '/' . $param['no']. '_thumb.jpg';

			// $thumb = new PicThumb();
			// $thumb->set_config($option);
			// $thumb->create_thumb($source, $thumb_file);


            $data['created'] = date('Y-m-d H:i:s');
            $pid = $this->Pattern_model->add($data);

			if (file_exists($data['picture'])) {
				$post_data = [
					'points' => $this->config->item('project_dir') . $data['picture'],
                    'patternNo'=>$param['no'],
                    'patternId'=> $pid,
				];
				$this->curl_post($this->config->item('cbir_url') . 'cbir_add', $post_data);
			}
        }


        $add  = [];
        foreach ($param['pro'] as $k => $v) {
            $add[] = array(
                'pid' => $pid,
                'property_key' => $k,
                'property_name' => $v['name'],
                'property_value' => json_encode(array('value' => $param[$k]), JSON_UNESCAPED_UNICODE)
            );
        }

        $this->Pattern_property_model->add($add);


        if (isset($param['pid'])) {
            $this->client->updateIndex($pid);
        } else {
            $this->client->addIndex($pid);
        }
        return true;
    }


    public function patternSearch($param, $export = false, $ids = array()) {
        if (!$export) {
            if (!isset($param['pageNo'], $param['pageSize'])) {
                exit(retJson(ErrCode::ErrCode_10002));
            }
        }
        $extra = "";
        $keyword = [];
        $conditions = [];

        if (isset($param['keyword']) && $param['keyword'] != '') {
            $keyword[] = $param['keyword'];
        }
      
        $arrKs = [
            ['useradio', '用途'],
            ['ClothingStyleradio', '款式'],
            ['elasticradio', '弹性'],
            ['Machinemodelradio', '机型'],
            ['NumberOfStitchesradio', '机台针数'],
            ['Machinefunctionradio', '功能'],
            ['texturesradio', '质感'],
            ['structureradio', '结构']
        ];

        foreach ($arrKs as $arrk) {
            if (!empty($param[$arrk['0']])) {
                $keyword[] = $param[$arrk['0']];
            }

            if (empty($extra)) {
            	if (!empty($param[$arrk['0']])) {
					$extra .= $arrk['1'] . ":" . $param[$arrk['0']];
				}
			} else {
            	if(!empty($param[$arrk['0']])) {
					$extra .= "|" . $arrk['1'] . ":" . $param[$arrk['0']];
				}
			}
        }

        $rules = [
            [
                'field' => 'search_way', 'value' => "关键词搜索", 'behavior' => true
            ],
            [
                'field' => 'season', 'value' => $param['DevelopmentSeasonvalue'], 'behavior' => true
            ],
            [
                'field' => 'year', 'value' => $param['yearvalue'], 'behavior' => true
            ],
            [
                'field' => 'word_img', 'value' => $param['keyword'], 'behavior' => true
            ],
            [
                'field' => 'initiator', 'value' => $this->role->username, 'behavior' => true
            ]
        ];


        if (!empty($param['DevelopmentSeasonvalue']) && !empty($param['yearvalue'])) {
            $rules[] = [
                'field' => 'season', 'value' => $param['DevelopmentSeasonvalue'], 'behavior' => true
            ];
            $rules[] = [
                'field' => 'year', 'value' => $param['yearvalue'], 'behavior' => true
            ];
        }
        if (!empty($param['FlowerHeightMin']) || !empty($param['FlowerHeightMax'])) {
            $rules[] = ['field' => 'height', 'from' => (float) $param['FlowerHeightMin'], 'to' => (float) $param['FlowerHeightMax']];
            $extra .= empty($extra) ? "花高:" . $param['FlowerHeightMin'] .'~'.$param['FlowerHeightMax'] : "|花高:" .  $param['FlowerHeightMin'] .'~'.$param['FlowerHeightMax'];
        }
        if (!empty($param['HightohighInputMin']) || !empty($param['HightohighInputMax'])) {
            $rules[] = [
                'field' => 'widthheight', 'from' => (float) $param['HightohighInputMin'], 'to' => (float) $param['HightohighInputMax']
            ];
            $extra .= empty($extra) ? "幅宽(高对高):" . $param['HightohighInputMin'] . "~" . $param['HightohighInputMax'] : "幅宽(高对高):" . $param['HightohighInputMin'] . "~" . $param['HightohighInputMax'] . "|";
        }
        if (!empty($param['LowtolowInputMin']) || !empty($param['LowtolowInputMax'])) {
            $rules[] = [
                'field' => 'widthlow', 'from' => (float) $param['LowtolowInputMin'], 'to' => (float) $param['LowtolowInputMax']
            ];
            $extra .= empty($extra) ? "幅宽(低对低):" . $param['LowtolowInputMin'] . "~" . $param['LowtolowInputMax'] : "幅宽(低对低):" . $param['LowtolowInputMin'] . "~" . $param['LowtolowInputMax'] . "|";
        }

        // 处理克重
		if (!empty($param['WeightMin']) || !empty($param['WeightMax'])) {
			$rules[] = [
				'field' => 'weight', 'from' => (float) $param['WeightMin'], 'to' => (float) $param['WeightMax']
			];
			$extra .= empty($extra) ? "克重:" . $param['WeightMin'] . "~" . $param['WeightMax'] : "克重:" . $param['WeightMin'] . "~" . $param['WeightMax'] . "|";
		}

        if (!empty($param['materialstateClassification'])) {
        	$tmp = [
        		'type' => $param['materialstate'],
				'keywords' => $param['materialstateClassification']
			];

            $material = $this->addrules($param['materialstateClassification'], $param['materialstate']);
            $keyword[] = $tmp;
            $extra .= empty($extra) ? "材料:" . $material : "材料:" . $material . "|";
        }

        if (!empty($param['ElementdescriptionstateClassification'])) {
			$tmp = [
				'type' => $param['Elementdescriptionstate'],
				'keywords' => $param['ElementdescriptionstateClassification']
			];
			$keyword[] = $tmp;
            $Elementdescription = $this->addrules($param['ElementdescriptionstateClassification'], $param['Elementdescriptionstate']);
            $extra .= empty($extra) ? "波边:" . $Elementdescription : "波边:" . $Elementdescription . "|";
        }

        if (!empty($param['PatternstylestateClassification'])) {
			$tmp = [
				'type' => $param['Patternstylestate'],
				'keywords' => $param['PatternstylestateClassification']
			];
			$keyword[] = $tmp;

            $Patternstyle = $this->addrules($param['PatternstylestateClassification'], $param['Patternstylestate']);
            $extra .= empty($extra) ? "元素:" . $Patternstyle : "元素:" . $Patternstyle . "|";
        }

        if (!empty($param['overlockstateClassification'])) {
			$tmp = [
				'type' => $param['overlockstate'],
				'keywords' => $param['overlockstateClassification']
			];
			$keyword[] = $tmp;

            $overlock = $this->addrules($param['overlockstateClassification'], $param['overlockstate']);
            $extra .= empty($extra) ? "风格:" . $overlock : "风格:" . $overlock . "|";
        }


        $rules[] = [
            'field' => 'extra', 'value' => $extra, 'behavior' => true

        ];

        // 如果是客户
        if ($this->role->role_id == WebRole::Customer[TPEnum::Value]) {
			$customer = $this->Customer_model->get_single(['aid' => $this->role->id]);
			// 处理
			$rules[] = [
				'field' => 'level', 'value' => $customer['privilege_level'], 'behavior' => false
			];

            $rules[] = [
                'field' => 'customer', 'value' => $this->role->id, 'behavior' => true
            ];
            $rules[] = [
                'field' => 'cust_name', 'value' => $this->role->username, 'behavior' => true
            ];
            $rules[] = [
                'field' => 'cust_code', 'value' => $this->role->usercode, 'behavior' => true
            ];
        } else {
            $rules[] = [
                'field' => 'staff', 'value' => $this->role->id, 'behavior' => true
            ];
            $rules[] = [
                'field' => 'staff_name', 'value' => $this->role->username, 'behavior' => true
            ];
            if (!empty($param['customervalue'])) {
                $customer = $this->Account_model->get_single(['id' => $param['customervalue']]);
                $rules[] = [
                    'field' => 'customer', 'value' => $param['customervalue'], 'behavior' => true
                ];
                $rules[] = [
                    'field' => 'cust_name', 'value' => $customer['username'], 'behavior' => true
                ];
                $rules[] = [
                    'field' => 'cust_code', 'value' => $customer['usercode'], 'behavior' => true
                ];
            }
        }

        //查询权限内的花型
        $detail = $this -> Account_model -> get_single(array("uuid" =>$_SESSION[SESS_HEADER]['uuid']));
        $sql = sql_format("SELECT no from tp_pattern where is_public = 1 and is_delete = 0 and FIND_IN_SET({0},viewId) order by created desc", $detail['id']);
        $patterns = $this->Pattern_model->query($sql);
        $pattern_no = array_column($patterns,'no');    

        $newimgcode = array();
        if (!empty($param['InventorystateClassification'])) {  // 库存条件
            $Inventorylist = array();
            foreach($param['InventorystateClassification'] as $k=>$v){
                switch ($v) {
                    case '坯布仓库':
                        $Inventorylist[] = 'FPHang';
                        break;
                    case '半品仓库':
                        $Inventorylist[] = 'STMHang';
                        break;
                    case '成品仓库':
                        $Inventorylist[] = 'STHang';
                        break;
                }
            }
            $Inventory = implode(",", $Inventorylist);
           $newimgcode =  $this->getPatternInventorystateList($Inventory);
            // $newimgcode =array('HY7116N','HF8233P','HY6711NV','HY6790N');
            if($newimgcode){  //判断花型是否在可查看范围内
                foreach($newimgcode as $k=>$v){
                    if(!in_array($v,$pattern_no)){ //查看花型是否在权限范围内，权限范围内方可查看
                        unset($newimgcode[$k]);
                    }
                }
            }
            
        }



        // var_dump($extra);

        //2023-08-24修改之前
        //        $ret = $this->client->search($keyword, $rules, $param['pageSize'], $param['pageNo']);
        // $ret = $this->client->search2($keyword, $rules, $param['pageSize'], $param['pageNo'], $ids);
        // var_dump($ids);
        //2023-08-24修改之后
        $newids=array();
        $similarty = array();
        if (!empty($ids)){
            foreach($ids['data'] as $k=>$v){
                if($v['img_name'] != ""){
                    $img_name =explode("-",$v['img_name'])[0];
                    // $newids[$k] = strtolower(explode("-",$v['img_name'])[0])  ;
                    if(in_array($img_name,$pattern_no)){ //查看花型是否在权限范围内，权限范围内方可查看
                        $newids[$k] =   $img_name;
                        $similarty[$img_name] = $v['similarity'];
                    }
                   
                }
            }
        }
        // var_dump($newids);
        // var_dump($newimgcode);

        //当图片和库存条件同时存在的时候
        if(!empty($newimgcode) && !empty($newids)){ //有图片搜索有库存条件
            $newids =  array_unique(array_merge($newimgcode, $newids));
          
        }else if(!empty($newimgcode) && empty($newids)){//有库存条件无图片搜索
            $newids = $newimgcode;
        }else if(empty($newimgcode) && !empty($newids)){//有图片搜索无库存条件
            $newids = $newids;
        }else{  //无库存搜索，无库存条件
            $newids = $pattern_no; //合并权限的花型和条件筛选的花型
        }
            // var_dump($newids);
       
        if($pattern_no){
            $ret = $this->client->search2($keyword, $rules, $param['pageSize'], $param['pageNo'], $newids);
            //根据花型型号查询视图
            foreach($ret['items'] as $k=>$v){

                $ret['items'][$k]['similarity_value'] = isset($similarty[$v['no']])?$similarty[$v['no']]:'0';
            }
           
        }else{
            // if($_SESSION[SESS_HEADER]['uuid'] == '12121212'){//超级管理员查看全部
            //     $ret = $this->client->search2($keyword, $rules, $param['pageSize'], $param['pageNo'], $newids);
            //     //根据花型型号查询视图
            //     foreach($ret['items'] as $k=>$v){
    
            //         $ret['items'][$k]['similarity_value'] = isset($similarty[$v['no']])?$similarty[$v['no']]:'0';
            //     }
            // }else{
                $ret['items'] = array();
                $ret['total'] = 0;
            // }
            
            
        }

        $ret['totalPage'] = ceil($ret['total'] / $param['pageSize']);
        $ret['pageNo'] = $param['pageNo'];
    
    return $ret;
    }


     //根据库存条件搜索花型(调用存储过程)
     public function getPatternInventorystateList($Inventory){
        $configDateBase =  $this->config->item('sqlServerDatabase');
        // var_dump($configDateBase);
        $conn = new PDO("sqlsrv:server=".$configDateBase['server'].";database=".$configDateBase['database'],$configDateBase['uid'],$configDateBase['pwd']);
        // $sql="call spStockForSouhua(".$Inventory.")";
        // $sql="EXEC dbo.NewProc '".$Inventory."'";//创建存储过程查询语句
        $sql="EXEC dbo.spStockForSouhua '".$Inventory."'";//创建存储过程查询语句
        $conn->query($sql);
        $res = $conn->query("select * from dbo.MaterialNo_0 ORDER BY nSTQty DESC");
         $rest = $res->fetchAll(PDO::FETCH_ASSOC);
         $newArr =  array_column($rest,'sMaterialNo');
        
        return  $newArr;
    }




    //拼接规则
    private function addrules($fication, $state) {
        $element = "";
        foreach ($fication as $value) {
            $isstate = empty($state) ? 'AND' : $state;
            $element .= empty($element) ? $value : " $isstate " . $value;
        }

        return $element;
    }

    public function PatternImgImport() {
        $suffix = $_FILES['file']['name'];
        $suffix = explode('.', $suffix);
        if ($suffix[1] == 'zip') {
            $path = $this->UploadService->UploadFile('img_upload', false);
            $outpath = "upload/flowerImg";
            $zip = new ZipArchive();
            $openRes = $zip->open($path['path']);


            $arr = [];
            // var_dump($openRes);
            if ($openRes === true) {
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $res = $zip->getNameIndex($i);
                    if (strstr($res, '-')) {
                        $result = substr($res, 0, strripos($res, "-"));
                    } else {
                        $result = substr($res, 0, strripos($res, "."));
                    }
                    $arr[$result][] =  $outpath . '/' . $res;
                }
                $zip->extractTo($outpath);
                $zip->close();
            }



            $update = [];
            $j = 0;
            foreach ($arr as $key => &$value) {
                $update[$j] = array(
                    'no' => $key,
                    'picture' => $value['0'],
                );
                unset($value['0']);
                $update[$j++]['otherImg'] = implode(",", $value);
            }
            $this->Pattern_model->update_bat($update, "no");
            return;
        } else {
            exit(retJson(ErrCode::ErrCode_10001));
        }
    }


    /**
     * 方法名 changePublic
     *
     * @Name changePublic
     * @Desc 批量公布
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      DJC
     * @Date 2022-03-08 15:23:16
     * @return      [type]                   [description]
     */
    public function changePublic($param) {
        if (!isset($param['time'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        $begin = date('Y-m-01', strtotime($param['time']));
        $end = date('Y-m-d', strtotime("$begin +1 month -1 day"));

        $sql = sql_format("UPDATE tp_pattern SET is_public = 1, publish_time = '{0}' WHERE public >= '{1}' AND public <= '{2}'", date('Y-m-d'), $begin, $end);

        $this->Pattern_model->execute($sql);

        $sql = sql_format("SELECT pid,no,is_public,public,publish_time,created from tp_pattern where public >= '{1}' AND public <= '{2}'", $begin, $end);
        $list = $this->Pattern_model->query($sql);
        foreach($list as $k=>$v){
            $this->client->updateIndex($v['pid']);
        }

        return true;
    }


     /**
     * 方法名 changePublic
     *
     * @Name changePublic
     * @Desc 批量设置可查看权限人员
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      DJC
     * @Date 2022-03-08 15:23:16
     * @return      [type]                   [description]
     */
    public function ChangeViewPeople($param) {
        if (!isset($param['ViewId']) || !isset($param['pids'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

     
        $ViewId =  implode(",",$param['ViewId']);//查看人员id
        $pids = $param['pids']; 

        //批量修改查看人员
        foreach($pids as $k=>$v){
            $sql = sql_format("UPDATE tp_pattern SET  viewId = '{0}' WHERE pid = '{1}' ;",$ViewId, $v);
            $this->Pattern_model->execute($sql);
        }
        //批量更新索引
        foreach($pids as $k=>$v){
            $this->client->updateIndex($v);
        }

        return true;
    }


    /**
     * @Desc     返回值-Controller返回页面去
     * @Author   pekey
     * @DateTime 2020-05-12T19:25:48+0800
     * @param    errorCode,错误代码枚举，包含错误代码，及错误信息
     * @param    boolean，返回是否正确
     * @param    array，数据
     * @param    array，其他数据
     * @return   [type]，返回json类型
     */
    function retJson($desc, $errorCode, $data = array(), $append = array()) {
        $ret = array();

        $ret[RET_CODE]   = $errorCode[TPEnum::Value];
        $ret[RET_MSG]    = $desc . $errorCode[TPEnum::Caption];
        $ret[RET_EN_MSG] = $errorCode[TPEnum::Append1];
        $ret[RET_STATUS] = checkRetStatus($errorCode);

        if (is_array($data)) {
            $ret[RET_DATA] = json_encode($data);
        } else {
            $ret[RET_DATA] = $data;
        }
        if (is_array($append)) {
            $ret[RET_APPEND] = json_encode($append);
        } else {
            $ret[RET_APPEND] = $append;
        }

        return json_encode($ret);
    }

    /**
	 * 图片搜索
	 */
	public function imageSearch($param) {
         $param = json_decode($param,true);
		if (file_exists($param['searchPicture'])) {
			$post_data = [
				'points' => $this->config->item('project_dir') . $param['searchPicture'],
				'page' => $param['pageNo']
			];

            //			$post_data = [
            //				'points' => 'new.jpg',
            //				'page' => $param['pageNo']
            //			];
            // var_dump($this->config->item('img_search_url'));

            // var_dump($post_data);exit;

			$json = $this->curl_post($this->config->item('img_search_url'), $post_data);

			$rt = json_decode($json, true);
            
            // 2023-08-22修改新格式
            // $rt= array(
            //     'data'=>array(
            //         '0'=>array(
            //             'similarity'=>'0.994',
            //             'img_name'=>'HB3182NV1',
            //         ),
            //         '1'=>array(
            //             'similarity'=>'0.756',
            //             'img_name'=>'HF8233P',
            //         ),
            //         '2'=>array(
            //             'similarity'=>'0.657',
            //             'img_name'=>'HZ6405N-9',
            //         ),
            //         '3'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ6535P1-9',
            //         ),
            //         '4'=>array(
            //             'similarity'=>'0.602',
            //             'img_name'=>'HZ5060P1-9',
            //         ),
            //         '5'=>array(
            //             'similarity'=>'0.589',
            //             'img_name'=>'HY5500N-9',
            //         ),
            //         '6'=>array(
            //             'similarity'=>'0.556',
            //             'img_name'=>'HZ6765PR-9',
            //         ),
            //         '7'=>array(
            //             'similarity'=>'0.552',
            //             'img_name'=>'GZ5321N-9',
            //         ),
            //         '8'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ5437N-9',
            //         ),
            //         '9'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'GZ6812N-9',
            //         ),
            //         '10'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HY3798N-9',
            //         ),
            //         '11'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ6555NR-9',
            //         ),
            //         '12'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HY4983N-9',
            //         ),
            //         '13'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ5660N-9',
            //         ),
            //         '14'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ2775N2-9',
            //         ),
            //         '15'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HY6189NV-9',
            //         ),
            //         '16'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ6393P-9',
            //         ),
            //         '17'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ6458NR-9',
            //         ),
            //         '18'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ6579N-9',
            //         ),
            //         '19'=>array(
            //             'similarity'=>'0.64',
            //             'img_name'=>'HZ0780N1-9',
            //         )
                    
            //     ),
            //     'code'=>1
            // );

             //2023-08-22修改之前格式
            // $rt = array('GZ6716N','HY6802N','HZ6405N','HZ6535P1','HZ5060P1','HY5500N');
            // $rt = array('HZ6535P1');
                
        if($rt){
            $items = $this->patternSearch($param, false, $rt);
            $temp_items = [];
            $list = [];

            foreach ($items['items'] as $item) {
                $temp_items[$item['no']] = $item;
            }

            $newrt=array();
            foreach($rt['data'] as $k=>$v){
                if($v['img_name'] != ""){
                    $newrt[$k] = explode("-",$v['img_name'])[0]  ;
                }
            }

            if($newrt){
                // 重新排序
                foreach ($newrt as $no) {
                    if (isset($temp_items[$no])) {
                        $list[] = $temp_items[$no];
                    }
                }
            }
            return array(
                'items' => $list,
                'total' => $items['total'],
                'totalPage' => $items['totalPage'],
                'pageNo' => $param['pageNo']
            );
        }else{
            exit(retJson(ErrCode::ErrCode_11004));
        }
		
		}

		exit(retJson(ErrCode::ErrCode_10001));
	}

	private function curl_post($url,$post_data)
	{
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		$output = curl_exec($ch);
		curl_close($ch);
		return  $output;
	}

	public function checkParam($param) {
		$mergeSearch = false;

		$arrKs = [
			['useradio', '用途'],
			['ClothingStyleradio', '款式'],
			['elasticradio', '弹性'],
			['Machinemodelradio', '机型'],
			['NumberOfStitchesradio', '机台针数'],
			['Machinefunctionradio', '功能'],
			['texturesradio', '质感'],
			['structureradio', '结构']
		];

		foreach ($arrKs as $arrk) {
			if (!empty($param[$arrk['0']])) {
				$mergeSearch = true;
			}
		}

		if (!empty($param['FlowerHeightMin']) || !empty($param['FlowerHeightMax'])) {
			$mergeSearch = true;
		}
		if (!empty($param['HightohighInputMin']) || !empty($param['HightohighInputMax'])) {
			$mergeSearch = true;
		}
		if (!empty($param['LowtolowInputMin']) || !empty($param['LowtolowInputMax'])) {
			$mergeSearch = true;
		}

		if (!empty($param['WeightMin']) || !empty($param['WeightMax'])) {
			$mergeSearch = true;
		}

		if (!empty($param['materialstateClassification'])) {
			$mergeSearch = true;
		}
		if (!empty($param['ElementdescriptionstateClassification'])) {
			$mergeSearch = true;
		}
		if (!empty($param['PatternstylestateClassification'])) {
			$mergeSearch = true;
		}
		if (!empty($param['overlockstateClassification'])) {
			$mergeSearch = true;
		}

		return $mergeSearch;
	}

    //获取所有员工信息
    public function getAdminList(){
        $connar['items'] = "id,usercode,username,account_type,email";
        // $connar['where']=sql_format("role_id<>{0} and account_type = 1",1);
        $connar['where']=sql_format("account_type = {0}",1);
        $list = $this->V_Admin_model->get_list_full($connar);
        $newlist=array();
        foreach($list as $k=>$v){
            $newlist[$k]['value'] = $v['id'];  
            $newlist[$k]['label'] = $v['username']."【".$v['usercode']."】";  
        }
        return $newlist;
    }
}
